import React, { useEffect, useCallback, useState, useRef } from "react";
import { Modal } from "antd";
import { openNotificationWithIcon } from '@/utils/comm';
import ColumnSettingArrayTable from './components/ColumnSettingArrayTable';
import arrayTableContext from './components/arrayTableContext';

import styles from './CodeSetter.less';

const formEditorStyle = (/* label, */ children) => (
  <div style={{ marginBottom: 24 }}>
    {/* <div style={{marginBottom: 4}}>
      { label || ''}
    </div> */}
    {children}
  </div>
);

const VariableLengthTableColumnSetter = props => {
  const { value, onChange, label } = props;
  const [errorMsg/* ,  setErrorMsg */] = useState('');
  const [modalVisible, setModalVisible] = useState(false);

  const pageOperationRef = useRef({});
  const setPageOperation = useCallback((key, operation) => {
    pageOperationRef.current[key] = operation;
  }, []);

  useEffect(() => {
    if (!value || value.length === 0) {
      onChange([ 
        { title: '第1列', key: 'col0', type: 'input', required: false },
        { title: '第2列', key: 'col1', type: 'select', required: false, options: '选项1,选项2' },
      ]);
    }
  }, []);
  
  const formActionsRef = useRef(null);
  const setCurrentPageRef = useRef(null);
 
  return formEditorStyle(
    /* props.label, */
    <div className={styles.root}>
      <div className={styles.container}>
        <span>{label}</span>
        <a
          onClick={useCallback((e) => {
            e.preventDefault();
            setModalVisible(true);
          }, [])}
        > 
          设置
        </a>
      </div>
      <Modal
        width={1024}
        title="列项设置"
        visible={modalVisible}
        onOk={() => {
          if (formActionsRef.current) {
            formActionsRef.current
              .submit( ({ columns }) => {
                if (columns) {
                  let errorIndex;
                  const keyMap = {};
                  const valid = columns.every(({ key, type, title, options }, index) => {
                    if (keyMap[key]) {
                      openNotificationWithIcon('error', '', '列编码不能重复');
                      return false;
                    } else {
                      keyMap[key] = true;
                    }
                    const result = title && type && (
                      type === 'input' || 
                      (type === 'select' && options)
                    );
                    if (errorIndex === undefined && !result) {
                      errorIndex = index;
                    }
                    return !!result;
                  });
                  if (valid) {
                    return columns;
                  } else if (errorIndex !== undefined && pageOperationRef.current.columns) {
                    const { current, pageSize, setPage } = pageOperationRef.current.columns;
                    const errorPage = errorIndex / pageSize + 1;
                    if (current !== errorPage) {
                      setPage(errorPage, () => {
                        if (formActionsRef.current) {
                          formActionsRef.current.validate();
                        }
                      });
                    }
                    return null;
                  } else {
                    return null;
                  }
                }
                return columns || [];
              })
              .then(({ payload: columns }) => {
                if (columns) {
                  // window.console.log('subvmit value', payload);
                  onChange(columns);
                  setModalVisible(false);
                }
              })
          }
        }}
        onCancel={() => setModalVisible(false)}
        okButtonProps={{
          disabled: !!errorMsg,
        }}
      >
        <arrayTableContext.Provider value={{ setPageOperation }}>
          <ColumnSettingArrayTable
            value={{ columns: value }}
            getFormAction={actions => { formActionsRef.current = actions; }}
            getPageSetter={setter => { setCurrentPageRef.current = setter; }}
          />
        </arrayTableContext.Provider>
        <div className={errorMsg ? 'ant-form-item-has-error' : ''}>
          { errorMsg ? (
            <div className="ant-form-item-explain ant-form-item-explain-error">
              <div role="alert">{errorMsg}</div>
            </div>
          ) : null }
        </div>
      </Modal>
    </div>
  );
};

export const CodeSetterName = "ArrayTableColumnSetter";
export default VariableLengthTableColumnSetter;
